package com.cskaoyan.wordmemorize.controller.admin;

import cn.dev33.satoken.stp.StpUtil;
import com.cskaoyan.wordmemorize.auth.StpKit;
import com.cskaoyan.wordmemorize.common.result.Result;
import com.cskaoyan.wordmemorize.common.util.IpUtil;
import com.cskaoyan.wordmemorize.dto.admin.AdminLoginDTO;
import com.cskaoyan.wordmemorize.dto.admin.EmployeeDTO;
import com.cskaoyan.wordmemorize.dto.admin.RolePermissionDTO;
import com.cskaoyan.wordmemorize.request.EmployeeLoginRequest;
import com.cskaoyan.wordmemorize.service.EmployeeService;
import com.cskaoyan.wordmemorize.service.RolePermissionService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
@RequestMapping("admin")
public class LoginController {

    @Resource
    EmployeeService employeeService;

    //后台员工登录
    @PostMapping("login")
    public Result<AdminLoginDTO> login(@RequestBody EmployeeLoginRequest loginRequest, HttpServletRequest request){

        //匹配登录时的用户名和密码
        EmployeeDTO employee = employeeService.login(loginRequest.getUsername(), loginRequest.getPassword());

        //登录成功开启登录会话：account_session
        String idStr = employee.getId();
        long idL = Long.parseLong(idStr);
        StpKit.ADMIN.login(idL);

        //更新用户登录ip，时间
        employeeService.updateLoginInfo(idL, IpUtil.getIpAddr(request), LocalDateTime.now());

        //获取登录的account_session对应的token
        String token = StpKit.ADMIN.getTokenValue();
        AdminLoginDTO adminLoginDTO = new AdminLoginDTO();
        adminLoginDTO.setToken(token);
        return Result.ok(adminLoginDTO);

    }

    //后台员工登出
    @PutMapping("logout")
    public Result<String> logout() {

        StpUtil.logout();
        return Result.ok("当前会话是否登录：" + StpUtil.isLogin());
    }

    @Autowired
    RolePermissionService rolePermissionService;

    // 获取角色对应的授权信息
    @GetMapping("/{roleId}/permission/list")
    public Result<RolePermissionDTO> rolePermissionList(@PathVariable("roleId") String roleId){
        RolePermissionDTO rolePermissionList =
                rolePermissionService.getRolePermissionList(Long.valueOf(roleId));
        return Result.ok(rolePermissionList);
    }
}
